﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using LsUpdater.API;
using System.Diagnostics;
using System.IO;


namespace LsUpdater
{
    public partial class ProcessFrm : Form
    {
        public ProcessFrm()
        {
            InitializeComponent();

        }
        private Thread threadUpdate = null;
        private int TimeOut = 3000;
        //private void btnFinish_Click(object sender, EventArgs e)
        //{
        //    this.Hide();
        //    //启动文件
        //    Environment.Exit(0);
        //}

        private void ProcessFrm_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
            //lblAppName.Text = string.Format(lblAppName.Text, UpdateHelper.Instance.AppName);
            //lblUpdateVersion.Text = string.Format(lblUpdateVersion.Text, UpdateHelper.Instance.UpdateVersion);

            FTHelper.Instance.DownloadProcessing += new EventHandler(ft_DownloadProcessing);
            FTHelper.Instance.DownloadComplete += new EventHandler(Instance_DownloadComplete);
            FTHelper.Instance.PreDownload += new EventHandler(Instance_PreDownload);
            //StartDownLoad();
            threadUpdate = new Thread(new ThreadStart(StartDownLoad));
            threadUpdate.Start();
            progressBar1.Maximum = 100;
            progressBar1.Minimum = 0;
            progressBar1.Step = 1;



        }

        void Instance_PreDownload(object sender, EventArgs e)
        {
            FTHelper.Instance.Downbytes = 0;
             progressBar1.Value = 0;
        }

        void Instance_DownloadComplete(object sender, EventArgs e)
        {
           
        }
    

        void Instance_UpdateSuccess(object sender, EventArgs e)
        {
            this.Hide();
            FinishFrm finishfrm = new FinishFrm();
            finishfrm.ShowDialog();

            //btnCancel.Enabled = true;
        }


        private void StartDownLoad()//开始下载升级程序
        {
            int i = 1;
            foreach (var item in LsUpdater.API.Comm.listc)
            {
                lblFileName.Text = "正在下载：" + item.path;
                lblstatus.Text = "当前状态:正在下载" + i + " / " + LsUpdater.API.Comm.listc.Count;
                FTHelper.Instance.Download(LsUpdater.API.Comm.infoRemote.RemoteDir + item.path, System.AppDomain.CurrentDomain.BaseDirectory + "\\update\\");
                i++;
            }  
            
           //执行第二步.
            UpdateStep2();
          
        }

        void download_InfoReceived(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
        }

        void ft_DownloadProcessing(object sender, EventArgs e)
        {
            //处理状态
            progressBar1.Value = Convert.ToInt32(FTHelper.Instance.Downbytes * 100 / FTHelper.Instance.AllBytes);
            lblRate.Text = "进度:" + float.Parse((FTHelper.Instance.Downbytes * 100 / FTHelper.Instance.AllBytes).ToString()) + "%";
            this.lblNum.Text = "" + (FTHelper.Instance.Downbytes / 1024).ToString("n") + "KB/" + (FTHelper.Instance.AllBytes / 1024).ToString("n") + "KB";
        }

        private void ProcessFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Environment.Exit(0);
        }

        private void progressBar1_Click(object sender, EventArgs e)
        {

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("你的更新尚未完成,确认退出吗?", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
            {
                Environment.Exit(0);
            }
        }
        #region 下载完成后覆盖原来的目录
        private void UpdateStep2()
        {
            lblstatus.Text = "当前状态:正在升级";
            if (IsLiveProcess(Comm.infoRemote.ProcessName))
            {
                if (DialogResult.OK == MessageBox.Show("当前程序正在运行,需要关闭才能完成升级,确认关闭吗?", "确认关闭程序", MessageBoxButtons.OKCancel))
                {
                    KillProcess(Comm.infoRemote.ProcessName);
                }
                else
                {
                    Environment.Exit(0);
                    return;
                }
            }
            while (true)
            {
                if (!IsLiveProcess(Comm.infoRemote.ProcessName))
                {                    
                    FileHelper.CopyDir(System.AppDomain.CurrentDomain.BaseDirectory + "\\update", System.AppDomain.CurrentDomain.BaseDirectory);                          
                    break;
                }
            }
            FileHelper.DeleteFolder(System.AppDomain.CurrentDomain.BaseDirectory + "\\update");
            //清理未使用文件
            foreach (var item in Comm.listClearList)
            {
                if (File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + item.path))
                {
                    FileHelper.FileDel(System.AppDomain.CurrentDomain.BaseDirectory + "\\" + item.path);
                }
            }

            this.Hide();
            FinishFrm finishfrm = new FinishFrm();
            finishfrm.ShowDialog();
            
        }

        private bool IsLiveProcess(string processName)
        {
            Process[] MyProcesses = Process.GetProcesses();
            foreach (var item in MyProcesses)
            {
                if (item.ProcessName == processName)
                {
                    return true;
                }
            }
            return false;
        }

        #region 杀死进程
        private void KillProcess(string processName)
        {
            //获得进程对象，以用来操作   
            System.Diagnostics.Process myproc = new System.Diagnostics.Process();
            //得到所有打开的进程    
            try
            {
                //获得需要杀死的进程名   
                foreach (Process thisproc in Process.GetProcessesByName(processName))
                {
                    //立即杀死进程   
                    thisproc.Kill();
                }
            }
            catch (Exception Exc)
            {
                throw new Exception("", Exc);
            }
        }
        #endregion
        #endregion

    }
}
